package main

import (
	"BanlanceProxy/proxy"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

func main() {
	//ch := make(chan bool)
	//httpServer()
	config, err := ReadConfig("config.yaml")
	if err != nil {
		log.Fatalf("read config error: %s", err)
	}
	err = config.Validation()
	if err != nil {
		log.Fatalf("verify config error: %s", err)
	}
	if config.Server_Web == "web" {

		httpServer(config)
	} else {
		gins(config)
	}

	//<-ch
}

func httpServer(config *Config) {

	for _, l := range config.Location {

		httpProxy, err := proxy.NewHTTPProxy(l.ProxyPass, l.BalanceMode)
		if err != nil {
			log.Fatalf("create proxy error: %s", err)
		}
		// start health check
		if config.HealthCheck {
			httpProxy.HealthCheck(config.HealthCheckInterval)
		}
		//router.Handle(l.Pattern, httpProxy)
		http.Handle(l.Pattern, httpProxy)

	}
	//http.Handle("/", httpProxy)
	fmt.Println(":", config.Port, " 服务启动。。。。。。。")
	err := http.ListenAndServe(":"+strconv.Itoa(config.Port), nil)
	if err != nil {
		fmt.Println(":", config.Port, "服务启动失败,错误信息：", err)
		return
	}

	// start health check

}

// 配置跨域
func configCors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Header("Access-Control-Allow-Headers", "*")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		// 处理请求
		c.Next()
	}
}
func gins(config *Config) {
	r := gin.Default()
	r.Use(configCors())

	//var list []*proxy.HTTPProxy
	for _, l := range config.Location {

		httpProxy, err := proxy.NewHTTPProxy(l.ProxyPass, l.BalanceMode)
		if err != nil {
			log.Fatalf("create proxy error: %s", err)
		}
		// start health check
		if config.HealthCheck {
			httpProxy.HealthCheck(config.HealthCheckInterval)
		}
		//router.Handle(l.Pattern, httpProxy)
		//http.Handle(l.Pattern, httpProxy)
		//list = append(list, httpProxy)
		r.GET("/", func(c *gin.Context) {
			httpProxy.ServeHTTP(c.Writer, c.Request)
		})
	}

	fmt.Println(":", config.Port, " 服务启动。。。。。。。")
	err := r.Run(":" + strconv.Itoa(config.Port))
	if err != nil {
		fmt.Println(":", config.Port, "服务启动失败,错误信息：", err)
		return
	}
}
